<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <ElButton :icon="Plus" type="primary" @click="action({}, 0)">{{
        t('exampleDemo.add')
      }}</ElButton>
      <ElButton type="primary" @click="exportXls">
        <Icon icon="uil:import" color="white" />&nbsp;{{ t('dataDictionary.export') }}
      </ElButton>
      <ElButton :loading="delLoading" @click="delData(null, true)">
        {{ t('announcement.dels') }}
      </ElButton>
    </div>

    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :pagination="{
        total: tableObject.total
      }"
      row-key="id"
      @register="register"
    >
      <template #action="{ row }">
        <ElButton link type="primary" v-if="row.sendStatus == 0" @click="action(row, 1)">
          {{ t('exampleDemo.edit') }}
        </ElButton>
        <el-dropdown style="margin-left: 20px; vertical-align: middle">
          <el-button link type="primary">
            {{ t('menuTable.more') }}<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item v-if="row.sendStatus != 1" @click="delData(row, false)">{{
                t('menuTable.del')
              }}</el-dropdown-item>
              <el-dropdown-item v-if="row.sendStatus == 0" @click="release(row.id, true)">
                {{ t('menuTable.release') }}
              </el-dropdown-item>
              <el-dropdown-item v-if="row.sendStatus == 1" @click="release(row.id, false)">
                {{ t('menuTable.revoke') }}
              </el-dropdown-item>
              <el-dropdown-item @click="action(row, 2)">{{ t('menuTable.view') }}</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
    </Table>
  </ContentWrap>
</template>

<script setup lang="ts" name="announcement">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import {
  getAnnountCementListApi,
  dictExportXls,
  deleteBatchIdApi,
  delIdApi,
  doReleaseDataIdApi,
  doReovkeDataIdApi
} from '@/api/modules/systemMessage'
import { AnnouncementTableData } from '@/api/modules/type'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useEmitt } from '@/hooks/web/useEmitt'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { downXls } from '@/api/common/import'
import { ArrowDown, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { debounce } from 'lodash-es'
const { push } = useRouter()

const { register, tableObject, methods } = useTable<AnnouncementTableData>({
  getListApi: getAnnountCementListApi,
  delListApi: delIdApi,
  delAllListApi: deleteBatchIdApi,
  defaultParams: {
    column: 'createTime',
    order: 'desc',
    field: 'id,,,title,msgCategory,sender,priority,msgType,sendStatus,sendTime,cancelTime,action'
  },
  response: {
    res: 'records',
    list: 'result',
    total: 'total'
  }
})
const { getList, setSearchParams } = methods

getList()

useEmitt({
  name: 'getList',
  callback: (type: string) => {
    if (type === 'add') {
      tableObject.currentPage = 1
    }
    getList()
  }
})

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: t('announcement.index'),
    type: 'index'
  },
  {
    field: 'title',
    label: t('announcement.title'),
    search: {
      show: true
    }
  },
  {
    field: 'msgCategory_dictText',
    label: t('announcement.msgCategory_dictText')
  },
  {
    field: 'sender',
    label: t('announcement.sender')
  },
  {
    field: 'priority_dictText',
    label: t('announcement.priority_dictText')
  },
  {
    field: 'msgType_dictText',
    label: t('announcement.msgType_dictText')
  },
  {
    field: 'sendTime',
    label: t('announcement.sendTime'),
    width: '220px'
  },
  {
    field: 'cancelTime',
    label: t('announcement.cancelTime'),
    width: '220px'
  },
  {
    field: 'action',
    label: t('tableDemo.action'),
    width: '220px'
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const delLoading = ref(false)

// 删除
const delData = async (row: AnnouncementTableData | null, multiple: boolean) => {
  tableObject.currentRow = row
  const { delList, getSelections } = methods
  const selections = await getSelections()
  delLoading.value = true
  await delList(
    multiple
      ? { ids: selections.map((v) => v.id).join(',') }
      : { id: tableObject.currentRow?.id as string },
    multiple
  ).finally(() => {
    delLoading.value = false
  })
}
// 发布
const release = debounce(async (id, type) => {
  let res
  type ? (res = await doReleaseDataIdApi({ id })) : (res = await doReovkeDataIdApi({ id }))
  if (res.success) {
    ElMessage.success(res.message || '操作成功')
    methods.getList()
  } else {
    ElMessage.error(res.message)
  }
}, 100)

// 导出
const exportXls = debounce(async () => {
  const params = Object.assign(tableObject.params, {
    pageSize: tableObject.pageSize,
    pageNo: tableObject.currentPage
  })
  let result = await dictExportXls('/sys/annountCement/exportXls', params)
  if (+result.status === 200) {
    downXls(result, '系统通告', '')
  }
}, 100)
const action = (row: AnnouncementTableData, type: number) => {
  push(`/system/announcement/add?type=${type}&row=${JSON.stringify(row)}`)
}
</script>
